Ruby 將方法定義從僵化的簽名提升至 動態介面。透過掌握 Splat 運算子與基於表達式的邏輯,我們能創造出能自然適應不同資料密度的方法,無需複雜的重載機制。
1. 智慧預設值與 Splat
Ruby 允許參數在簽名中初始化,即使資料量很少也能確保功能正常。 Splat 運算子 (*) 它就像一座橋樑:在參數中,將額外的引數收集到一個陣列中;在呼叫時,則將陣列「炸開」成單獨的槽位。
2. 基於表達式的回傳
Ruby 方法會自動回傳 最後執行的表達式。然而, return 關鍵字會策略性地使用,以提早退出或將多個值以陣列形式回傳,供 平行賦值使用。
num, sq = meth_three
# Ruby 將 (num, sq) 打包成陣列 [32, 1024]
# Ruby 將 (num, sq) 打包成陣列 [32, 1024]
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What is the primary role of the asterisk (*) in a method parameter list?
To mark a variable as a pointer to a memory address.
To capture a variable number of arguments into a single array.
To multiply the incoming argument by its index.
To indicate the method is private.
✅ Correct!
In a signature, `*` bundles all 'extra' arguments into an array named after the parameter.❌ Incorrect
In Ruby, `*` in parameters is the 'splat' operator used for variable-length argument lists.QUESTION 2
Given `def show(x, y=10)`, what happens if you call `show(5)`?
An ArgumentError is raised because two arguments are required.
x becomes 5 and y becomes 10.
x becomes 5 and y becomes nil.
The method returns 15 automatically.
✅ Correct!
Since y has a default value of 10, the method proceeds using that default when the second argument is omitted.❌ Incorrect
Default values allow methods to be functional even when the caller provides minimal data.QUESTION 3
What does 'Array Expansion' (Exploding) refer to in a method call?
Converting a string into an array of characters.
Deleting all elements in an array to free memory.
Using `*` before an array to pass its elements as individual arguments.
Expanding the heap to accommodate larger arrays.
✅ Correct!
Using `*arr` in a call 'explodes' the array, filling the method's parameter slots one by one.❌ Incorrect
Expansion refers to satisfying individual parameters using the contents of a single array.QUESTION 4
If a Ruby method has no explicit `return` keyword, what does it return?
It returns nil by default.
It returns true if the code executed successfully.
It returns the value of the last expression evaluated.
It returns the name of the method as a string.
✅ Correct!
Ruby is expression-based; the result of the final line is the implicit return value.❌ Incorrect
Unless interrupted by an explicit `return`, Ruby always passes back the result of the last expression.QUESTION 5
How are multiple return values handled in `return a, b`?
Ruby only returns the first value (a).
Ruby returns an array `[a, b]` which can be destructured.
It results in a syntax error; only one value can be returned.
The values are added together before returning.
✅ Correct!
Ruby packages multiple values into an array, allowing for clean parallel assignment like `x, y = meth()`.❌ Incorrect
Multiple values are conveniently bundled into an array for the caller.Flexible Logging System Case Study
Designing an adaptive interface
You are building a logging system. Usually, you only pass a message. Occasionally, you need to pass a list of error codes. You define the method: `def log(msg='Info', *codes)`. The codes should be joined into a string if present.
Q
If you call `log()`, what are the values of `msg` and `codes` inside the method?
Solution:
`msg` will be 'Info' (the default value) and `codes` will be an empty array `[]`.
`msg` will be 'Info' (the default value) and `codes` will be an empty array `[]`.
Q
If you have an array `errs = [404, 500]`, how do you call `log` so 'Critical' is the message and the errors are captured in the `codes` array?
Solution:
Call it using the splat operator: `log('Critical', *errs)`. This explodes the array into individual arguments after the first one.
Call it using the splat operator: `log('Critical', *errs)`. This explodes the array into individual arguments after the first one.
Q
How does Ruby's expression-based return benefit this logger if the last line is `codes.empty? ? msg : "#{msg}: #{codes.join(', ')}"`?
Solution:
The method automatically returns the formatted string without needing an explicit `return` keyword, making the code more concise and readable.
The method automatically returns the formatted string without needing an explicit `return` keyword, making the code more concise and readable.